package cn.fl.expatriate.service.impl;

import cmm.comm.facade.framework.api.ISysCdMapApiService;
import cmm.comm.facade.framework.condition.SysCdMapDQueryCondition;
import cmm.comm.facade.framework.dto.SysCdMapDDTO;
import cmm.comm.facade.syssms.api.ISmsAddApiService;
import cmm.comm.facade.syssms.dto.SmsSendParamDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.dto.SysUsrDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.capital.constant.CapPayInfoConstant;
import cn.fl.capital.service.ICapPayInfoService;
import cn.fl.capital.transform.CapPayInfoVOTransform;
import cn.fl.capital.vo.CapPayInfoVO;
import cn.fl.expatriate.api.IExpBizManRecApiService;
import cn.fl.expatriate.condition.ExpBizManRecQC;
import cn.fl.expatriate.constant.ExpBizManRecConstant;
import cn.fl.expatriate.dto.ExpBizManRecDTO;
import cn.fl.expatriate.service.IExpBizManRecService;
import cn.fl.expatriate.transform.ExpBizManRecVOTransform;
import cn.fl.expatriate.vo.ExpBizManRecVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjPrdDtlQueryCondition;
import cn.fl.project.dto.PrjPrdDtlDTO;
import cn.fl.project.service.IProjectApiService;
import com.alibaba.fastjson.JSON;
import fl.constant.facade.framework.constant.SystemConstant;
import flow.business.facade.flow.constant.FlowConstant;
import flow.business.facade.flow.dto.FlowStartParamsDTO;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 外派业务人员记录表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class ExpBizManRecServiceImpl implements IExpBizManRecService {

	/**
	 * 外派业务人员记录表 对外暴露接口
	 */
	@Autowired
	private IExpBizManRecApiService expBizManRecApiService;

	@Autowired
	private IProjectApiService projectApiService;

	/**
	 * 用户服务
	 */
	@Autowired
	private ISysUsrApiService sysUsrApiService;

	/**
	 * 短信接口
	 */
	@Autowired
	private ISmsAddApiService smsAddApiService;

	@Autowired
	private ICapPayInfoService capPayInfoService;

	@Autowired
	private ISysCdMapApiService sysCdMapApiService;

	@Override
	public ExpBizManRecVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.newLogger("selectById"+"主键参数不能为空!").info();
			return null;
		}
		//TODO 业务逻辑
		ExpBizManRecDTO dto = this.expBizManRecApiService.selectById(id);
		return ExpBizManRecVOTransform.toVO(dto);
	}

	@Override
	public Long add(ExpBizManRecVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.newLogger("add"+"新增对象不能为空!").info();
			return null;
		}
		//return this.expBizManRecApiService.add(ExpBizManRecVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return null;
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.newLogger("removeById"+ "删除主键参数不能为空!").info();
			return false;
		}
		//return this.expBizManRecApiService.removeById(id);
		//TODO 业务逻辑
		return false;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    @Override
	public boolean removeByIds(List<Long> ids)throws BaseException{
    	if(CollectionUtils.isEmpty(ids)){
			BaseLogUtils.newLogger("removeByIds"+ "删除主键参数集合不能为空!").info();
			return false;
		};
		return false;
    }

	@Override
	public boolean modify(ExpBizManRecVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.newLogger("modify"+ "修改对象参数不能为空!").info();
			return false;
		}
		//return this.expBizManRecApiService.modify(ExpBizManRecVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return false;
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page){
			page = new Pager();
		}
		//return this.expBizManRecApiService.searchListPage(page);
		//TODO 业务逻辑
		return null;
	}

	@Override
	public List<ExpBizManRecVO> searchList(ExpBizManRecQC expBizManRecQC) throws BaseException {
    	if (null == expBizManRecQC) {
			BaseLogUtils.newWebLogger("searchList"+"查询条件不能为空!").info();
			return null;
		}
		List<ExpBizManRecDTO> expBizManRecDTOList = this.expBizManRecApiService.searchList(expBizManRecQC);
		return ExpBizManRecVOTransform.toVOList(expBizManRecDTOList);
	}

	@Override
	public boolean saveExpBizManRec(ExpBizManRecVO entity) throws BaseException {
    	if (null == entity) {
			BaseLogUtils.newWebLogger("请求对象参数不能为空!").info();
		}
		Long prjId = entity.getDataId();
		String aptTypCd = entity.getAptTypCd();
		Long usrId = entity.getUsrId();
		String usrNm = entity.getUsrNm();
		String rlNm = entity.getRlNm();
		ExpBizManRecQC expBizManRecQC = new ExpBizManRecQC();
		expBizManRecQC.setDataId(prjId);
		expBizManRecQC.setAptTypCd(aptTypCd);
		expBizManRecQC.setDataTypCd("PRJ");
		expBizManRecQC.setIsDel(BaseConstant.IS_YESNO_NO);
		BaseLogUtils.newWebLogger("===查询业务外派人员记录Start===expBizManRecQC:" + JSON.toJSONString(expBizManRecQC)).info();
		List<ExpBizManRecDTO> expBizManRecDTOList = this.expBizManRecApiService.searchList(expBizManRecQC);
		BaseLogUtils.newWebLogger("===查询业务外派人员记录End===expBizManRecDTOList:" + JSON.toJSONString(expBizManRecDTOList)).info();
		if (CollectionUtils.isEmpty(expBizManRecDTOList)) {
			if (!"3".equals(aptTypCd)) {
				ExpBizManRecDTO expBizManRecDTO = new ExpBizManRecDTO();
				expBizManRecDTO.setDataId(prjId);
				expBizManRecDTO.setUsrId(usrId);
				expBizManRecDTO.setUsrNm(usrNm);
				expBizManRecDTO.setRlNm(rlNm);
				expBizManRecDTO.setAptTypCd(aptTypCd);
				expBizManRecDTO.setDataTypCd("PRJ");
				expBizManRecDTO.setIsDel(BaseConstant.IS_YESNO_NO);
				expBizManRecDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				expBizManRecDTO.setCrtUsrNm(CurrentThreadContext.getCurrentUserName());
				BaseLogUtils.newWebLogger("===新增业务外派人员记录Start===expBizManRecDTO:" + JSON.toJSONString(expBizManRecDTO)).info();
				Long id = this.expBizManRecApiService.add(expBizManRecDTO);
				BaseLogUtils.newWebLogger("===新增业务外派人员记录End===id:" + id).info();
				if (StringUtils.isEmpty(id)) {
					throw new BaseException("新增人员失败！");
				}
			} else {
				// 抵押 dtl
				this.dealExpManRecDtl(entity);
			}
		} else {
			for (ExpBizManRecDTO expBizManRecDTOForUp : expBizManRecDTOList) {
				expBizManRecDTOForUp.setUsrId(usrId);
				expBizManRecDTOForUp.setUsrNm(usrNm);
				expBizManRecDTOForUp.setRlNm(rlNm);
				expBizManRecDTOForUp.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				expBizManRecDTOForUp.setMdfTm(new Date());
				BaseLogUtils.newWebLogger("===修改业务外派人员记录Start===expBizManRecDTOForUp:" + JSON.toJSONString(expBizManRecDTOForUp)).info();
				boolean modify = this.expBizManRecApiService.update(expBizManRecDTOForUp);
				BaseLogUtils.newWebLogger("===修改业务外派人员记录End===modify:" + modify).info();
				if (!modify) {
					throw new BaseException("更新人员失败！");
				}
			}
			if ("3".equals(aptTypCd)) {
				this.dealExpManRecDtl(entity);
			}
		}
		return true;
	}

	/**
	 * 增加抵押人
	 * @param prjPrdDtlDTOList
	 * @param entity
	 */
	private void addExpManRecDtl(List<PrjPrdDtlDTO> prjPrdDtlDTOList, ExpBizManRecVO entity) {
		for (PrjPrdDtlDTO prjPrdDtlDTO : prjPrdDtlDTOList) {
			ExpBizManRecDTO expBizManRecDTO = new ExpBizManRecDTO();
			expBizManRecDTO.setDataId(prjPrdDtlDTO.getId());
			expBizManRecDTO.setAptTypCd(entity.getAptTypCd());
			expBizManRecDTO.setDataTypCd("DTL");
			expBizManRecDTO.setUsrId(entity.getUsrId());
			expBizManRecDTO.setUsrNm(entity.getUsrNm());
			expBizManRecDTO.setRlNm(entity.getRlNm());
			expBizManRecDTO.setIsDel(BaseConstant.IS_YESNO_NO);
			expBizManRecDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			expBizManRecDTO.setCrtUsrNm(CurrentThreadContext.getCurrentUserName());
			BaseLogUtils.newWebLogger("===新增业务外派人员抵押人记录Start===expBizManRecDTO:" + JSON.toJSONString(expBizManRecDTO)).info();
			Long id = this.expBizManRecApiService.add(expBizManRecDTO);
			BaseLogUtils.newWebLogger("===新增业务外派人员抵押人记录End===id:" + id).info();
			if (StringUtils.isEmpty(id)) {
				throw new BaseException("保存抵押人失败！");
			}
		}
	}

	/**
	 * 处理抵押人
	 * @param entity
	 */
	private void dealExpManRecDtl(ExpBizManRecVO entity) {
		PrjPrdDtlQueryCondition prjPrdDtlQC = new PrjPrdDtlQueryCondition();
		prjPrdDtlQC.setPrjId(entity.getDataId());
		prjPrdDtlQC.setSysCd(CurrentThreadContext.getCurrentSysCd());
		prjPrdDtlQC.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		prjPrdDtlQC.setIsDel(BaseConstant.IS_YESNO_NO);
		BaseLogUtils.newWebLogger("===查询项目产品信息Start===prjPrdDtlQC:" + JSON.toJSONString(prjPrdDtlQC)).info();
		List<PrjPrdDtlDTO> prjPrdDtlDTOList = this.projectApiService.selectPrjPrdDtlList(prjPrdDtlQC);
		BaseLogUtils.newWebLogger("===查询项目产品信息Start===prjPrdDtlDTOList-size:" + (CollectionUtils.isEmpty(prjPrdDtlDTOList)?0:prjPrdDtlDTOList.size())).info();
		if (CollectionUtils.isEmpty(prjPrdDtlDTOList)) {
			throw new BaseException("未查询到项目产品！");
		}
		List<Long> dtlIdList = new ArrayList<>();
		for (PrjPrdDtlDTO prjPrdDtlDTO : prjPrdDtlDTOList) {
			if (CollectionUtils.isEmpty(dtlIdList) || !dtlIdList.contains(prjPrdDtlDTO.getId())) dtlIdList.add(prjPrdDtlDTO.getId());
		}
		ExpBizManRecQC expBizManRecQCDtl = new ExpBizManRecQC();
		expBizManRecQCDtl.setDataIdList(dtlIdList);
		expBizManRecQCDtl.setAptTypCd(entity.getAptTypCd());
		expBizManRecQCDtl.setDataTypCd("DTL");
		expBizManRecQCDtl.setIsDel(BaseConstant.IS_YESNO_NO);
		BaseLogUtils.newWebLogger("===查询业务外派人员抵押人记录Start===expBizManRecQCDtl:" + JSON.toJSONString(expBizManRecQCDtl)).info();
		List<ExpBizManRecDTO> expBizManRecDTOListDtl = this.expBizManRecApiService.searchList(expBizManRecQCDtl);
		BaseLogUtils.newWebLogger("===查询业务外派人员抵押人记录End===expBizManRecDTOList:" + JSON.toJSONString(expBizManRecDTOListDtl)).info();
		if (CollectionUtils.isNotEmpty(expBizManRecDTOListDtl)) {
			for (ExpBizManRecDTO expBizManRecDTO : expBizManRecDTOListDtl) {
				expBizManRecDTO.setUsrId(entity.getUsrId());
				expBizManRecDTO.setUsrNm(entity.getUsrNm());
				expBizManRecDTO.setRlNm(entity.getRlNm());
				expBizManRecDTO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				expBizManRecDTO.setMdfTm(new Date());
				BaseLogUtils.newWebLogger("===修改业务外派人员抵押人记录Start===expBizManRecDTO:" + JSON.toJSONString(expBizManRecDTO)).info();
				boolean modify = this.expBizManRecApiService.update(expBizManRecDTO);
				BaseLogUtils.newWebLogger("===修改业务外派人员抵押人记录End===modify:" + modify).info();
				if (!modify) {
					throw new BaseException("更新抵押人失败！");
				}
			}
		} else {
			this.addExpManRecDtl(prjPrdDtlDTOList, entity);
		}
	}

	@Override
	public boolean sendSMS(String expIds, String lsCntNo) throws BaseException {
		try {
			List<String> expIdsList = new ArrayList<String>();
			JSONArray pkIdsArray = JSONArray.fromObject(expIds);
			for (Object object : pkIdsArray) {
				expIdsList.add(object.toString());
			}
			for (String expId : expIdsList) {
				ExpBizManRecDTO expBizManRecDTO = this.expBizManRecApiService.selectById(Long.valueOf(expId));
				String cstNm = "";//客户经理名称
				String mp = "";//客户经理手机号
				if (null != expBizManRecDTO && StringUtils.isNotEmpty(expBizManRecDTO.getUsrId())){
					BaseLogUtils.newWebLogger("===查询客户经理手机号Start===qc:" + JSON.toJSONString(expBizManRecDTO.getUsrId())).info();
					SysUsrDTO sysUsrDTO = this.sysUsrApiService.selectSysUsrById(expBizManRecDTO.getUsrId(), PropertiesCacheUtils.getProperty(SystemConstant.FL_SERVICE_CD), PropertiesCacheUtils.getProperty(SystemConstant.FL_ORG_CD));
					BaseLogUtils.newWebLogger("===查询客户经理手机号End===sysUsrDTO:" + JSON.toJSONString(sysUsrDTO)).info();
					if(null!=sysUsrDTO && StringUtils.isNotEmpty(sysUsrDTO.getMp())){
						mp = sysUsrDTO.getMp();
					}
					cstNm = expBizManRecDTO.getRlNm();

					SmsSendParamDTO smsSendParamDTO = new SmsSendParamDTO();
					smsSendParamDTO.setCode(ExpBizManRecConstant.EXP_SHORT_CODE_164);
					smsSendParamDTO.setMp(mp);

					smsSendParamDTO.setParams(new String[]{cstNm,lsCntNo});
					smsSendParamDTO.setType(0);
					BaseLogUtils.newWebLogger("===发送短信Start===smsSendParamDTO:" + JSON.toJSONString(smsSendParamDTO)).info();
					cmm.mid.core.framework.dto.DataResultDTO resultDTO = this.smsAddApiService.sendSMS(smsSendParamDTO);
					BaseLogUtils.newWebLogger("===发送短信End===resultDTO:" + JSON.toJSONString(resultDTO)).info();
					if(BaseConstant.IS_YESNO_YES_STR.equals(resultDTO.getCode())){
						BaseLogUtils.newServiceLogger("发送短信成功： " ).info();
					}else{
						BaseLogUtils.newServiceLogger("发送短信失败： "+resultDTO.getInfo()).info();
					}
				}
			}
		}catch (Exception e){
			BaseLogUtils.newWebLogger("系统异常,ex:" + JSON.toJSONString(e.getMessage())).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_700, "系统异常!");
		}
		return true;
	}

	@Override
	public DataResultVO mortgateExpFlowStart(Long capPayId) throws BaseException {
		BaseLogUtils.newLogger("发起抵押外派流程Start.capPayId:{}",capPayId).info();
		if (capPayId == null) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		CapPayInfoVO capPayInfoVO = capPayInfoService.selectById(capPayId);
		BaseLogUtils.newLogger("发起抵押外派流程查询付款信息End.capPayId:{},vo:{}", capPayId, JSON.toJSONString(capPayInfoVO)).info();
		if (capPayInfoVO == null || capPayInfoVO.getPrjPrdDtlId() == null) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "未查询到付款信息!");
		}
		//客户经理组织架构Cd
		String cstMgrOrgCd = capPayInfoVO.getCstMgrOrgCd();
		//项目类型
		String prjTypCd = capPayInfoVO.getPrjTypCd();
		//校验权限：重卡事业部-改装车业务部，传统业务
		if (!"CTYW".equals(prjTypCd)) {
			throw new BaseException("无发起抵押外派流程权限.");
		}
		BaseLogUtils.newLogger("抵押外派流程capPayId:{},当前用户组织架构cd:{},组织架构:{}", capPayId, JSON.toJSONString(CurrentThreadContext.getCurrentOrgCd()), CurrentThreadContext.getCurrentOrgShtNm()).info();
		SysCdMapDQueryCondition sysCdMapDQC = new SysCdMapDQueryCondition();
		sysCdMapDQC.setSysCd(CurrentThreadContext.getCurrentSysCd());
		sysCdMapDQC.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		sysCdMapDQC.setmTypCd("M1076");
		List<String> getsCodeList = new ArrayList<>();
		getsCodeList.add("orgCd");
		sysCdMapDQC.setsCodeList(getsCodeList);
		BaseLogUtils.newLogger("抵押外派流程查询映射的流程KEY开始.capPayId:{},condition:{}", capPayId, JSON.toJSONString(sysCdMapDQC)).info();
		List<SysCdMapDDTO> sysCdMapDDTOs = this.sysCdMapApiService.searchSysCdMapDWithTargetList(sysCdMapDQC);
		BaseLogUtils.newLogger("抵押外派流程查询映射的流程KEY结束.capPayId:{},sysCdMapDDTOs:{}", capPayId, JSON.toJSONString(sysCdMapDDTOs)).info();
		boolean expFlowStartAbleFlag = false;
		if (CollectionUtils.isNotEmpty(sysCdMapDDTOs)) {
			for (SysCdMapDDTO sysCdMapDDTO : sysCdMapDDTOs) {
				String tCode = sysCdMapDDTO.getTCode();
				if (CurrentThreadContext.getCurrentOrgCd().contains(tCode) && StringUtils.isNotEmpty(cstMgrOrgCd) && cstMgrOrgCd.contains(tCode)) {
					expFlowStartAbleFlag = true;
				}
			}
		}
		BaseLogUtils.newLogger("抵押外派流程是否为可发起外派组织架构.capPayId:{},expFlowStartAbleFlag:{}", capPayId, expFlowStartAbleFlag).info();
		if (!expFlowStartAbleFlag) {
			throw new BaseException("无发起外派流程权限.");
		}
		String pDefKey = ExpBizManRecConstant.CODE_DY_EXP_FLOW_P_DEF_KEY;
		BaseLogUtils.newLogger("发起抵押外派流程获取流程发起参数Start.id:{},pDefKey:{}", capPayInfoVO.getId(), pDefKey).info();
		FlowStartParamsDTO paramsDTO = buildFlowStartObj(capPayInfoVO,pDefKey);
		BaseLogUtils.newLogger("发起抵押外派流程获取流程发起参数End.id:{},paramsDTO:{}", capPayInfoVO.getId(), JSON.toJSONString(paramsDTO)).info();
		DataResultVO resultVO = null;
		DataResultDTO resultDTO = this.expBizManRecApiService.addMortgateExpFlow(CapPayInfoVOTransform.toDTO(capPayInfoVO), paramsDTO);
		BaseLogUtils.newLogger("发起抵押外派流程End.id:{},resultDTO:{}", capPayInfoVO.getId(), JSON.toJSONString(resultDTO)).info();
		if (resultDTO != null) {
			resultVO = new DataResultVO(resultDTO.getSuccess(), resultDTO.getInfo(), resultDTO.getData());
		}
		return resultVO;
	}


	/**
	 * 获取流程发起参数
	 * @return
	 * @throws BaseException
	 */
	private FlowStartParamsDTO buildFlowStartObj(CapPayInfoVO capPayInfoVO, String pDefKey) throws BaseException {
		FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
		flowStartParamsDTO.setProcDefKey(pDefKey);
		flowStartParamsDTO.setBusinessKey(String.valueOf(capPayInfoVO.getPrjPrdDtlId()));
		flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
		flowStartParamsDTO.setWordsInTheTable(CapPayInfoConstant.CAP_FLOW_S_H_CAP);
		flowStartParamsDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
		flowStartParamsDTO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		flowStartParamsDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
		flowStartParamsDTO.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
		flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext.getCurrentUserId()));
		flowStartParamsDTO.setInitiatorNm(CurrentThreadContext.getCurrentUserName());
		flowStartParamsDTO.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);//优先级,可以在界面定义
		flowStartParamsDTO.setBusinessType(FlowConstant.FLOW_BUSINESS_TYP_CAP_PAY_INFO);
		flowStartParamsDTO.setModelTyp(ExpBizManRecConstant.CODE_DY_EXP_FLOW);//需要和流程配置中的模块类型匹配
		return flowStartParamsDTO;
	}

}
